import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/fingerprint/widgets/add_fingerprint/index.dart";
import "package:ct_pa_majordomo/pages/device/lock/fingerprint/widgets/detail/index.dart";
import "package:ct_pa_majordomo/pages/device/lock/fingerprint/widgets/list_item.dart";
import "package:ct_pa_majordomo/pages/device/widgets/device_header.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/empty_data/index.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:ttlock_flutter/ttlock.dart";

class Fingerprint extends StatefulWidget {
  final Map info;
  const Fingerprint({super.key, required this.info});

  @override
  State<StatefulWidget> createState() => _FingerprintState();

}

class _FingerprintState extends State<Fingerprint> {
  final ScrollController _scrollController = ScrollController();
  final List<String> _items = ["重置指纹"];
  List _list = [];
  int _total = 0;
  bool _isLoading = false;
  Map<String, dynamic> _params = {
    "pageNum": 1,
    "pageSize": 10,
    "lockId": "",
  };


  void _getFingerprints() async {
    try {
      EasyLoading.show();
      _isLoading = true;
      Map resData = await lockApi.getFingerprints(int.parse(widget.info["lockId"]), _params);
      _isLoading = false;
      setState(() {
        _list.addAll(resData["rows"] ??[]);
        _total = resData["total"] ?? 0;
      });
    } catch (error) {
      print(error);
    } finally {
      EasyLoading.dismiss();
    }
  }

  void _getLocalFingerprint() {
    try {
      EasyLoading.show();
      TTLock.getAllValidFingerprints(widget.info["lockData"], (fingerprintList) {
        EasyLoading.dismiss();
        setState(() {
          _list = fingerprintList;
        });
        print("本地数据：》》》》》》》》》》》$fingerprintList");
      }, (errorCode, errorMsg) {
        EasyLoading.showError("$errorCode, $errorMsg");
      });
    } catch(error) {
      EasyLoading.dismiss();
      print("error:>>>>>>$error");
    }
  }

  Future<void> _resetFingerprint() async {
    /// 重置指纹 清空锁内所有指纹
    /// 添加登录密码确认重置
    taiDialog(
      context: context,
      title: "确定重置指纹？",
      child: const Text("重置指纹后，锁内所有指纹将被清空，请谨慎操作。", textAlign: TextAlign.center,),
      onConfirm: (BuildContext taiContext) async {
        try {
          EasyLoading.show();
          await lockApi.resetFingerprint(int.parse(widget.info["lockId"]));
          EasyLoading.showToast("重置指纹成功");
          Stacker.pop(taiContext);
          Future.delayed(const Duration(seconds: 1));
          _refresh();
        } catch (error) {
          print("error: $error");
        }
      },
    );
  }

  Future<void> _delFingerprint(int fingerprintId) async {
    /// 删除指纹
    taiDialog(
      context: context,
      title: "确定删除指纹？",
      child: const Text("删除指纹后，指纹将无法使用。",textAlign: TextAlign.center,),
      onConfirm: (BuildContext taiContext) async {
        try {
          EasyLoading.show();
          await lockApi.deleteFingerprint(int.parse(widget.info["lockId"]), fingerprintId);
          EasyLoading.showToast("删除指纹成功");
          Stacker.pop(taiContext);
          Future.delayed(const Duration(seconds: 1));
          _refresh();
        } catch (error) {
          print("error: $error");
        }
      },
    );
  }


  Future<void> _refresh() async {
    _params["pageNum"] = 1;
    _list = [];
    _getFingerprints();
  }

  void _onScroll() {
    if (_isLoading || _list.length >= _total) return;
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      setState(() {
        _params["pageNum"] += 1;
        _getFingerprints();
      });
    }
  }

  @override
  void initState() {
    super.initState();
    // _getLocalFingerprint();
    _params["lockId"] = widget.info["lockId"];
    _getFingerprints();
    _scrollController.addListener(_onScroll);
  }



  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DeviceHeader(
        title: "指纹",
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        showSearch: false,
        actions: [
          DropdownButton(
            icon: const Padding(padding: EdgeInsets.only(right: 12), child: Icon(Icons.more_horiz, color: Colors.white,),),
            underline: const SizedBox(height: 0,),
            padding: EdgeInsets.all(0),
            onChanged: (value) {
              if (value == "重置指纹") {
                _resetFingerprint();
              }
            },
            items: _items.map((item) {
              return DropdownMenuItem(
                value: item,
                child: SizedBox(
                  height: 20,
                  child: Text(item),
                ),
              );
            }).toList(),
          ),
        ],
        floatOnPress: () {
          Stacker.pushNamed(Keys.DEVICE_LOCK_FINGERPRINT_ADD, arguments: widget.info);
        },
        children: [
          Positioned(
              width: MediaQuery.of(context).size.width,
              top: 0,
              left: 0,
              child: Container(
                  width: MediaQuery.of(context).size.width,
                  decoration: const BoxDecoration(
                    color: Colors.white,
                  ),
                  padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 6),
                  child: const SizedBox(
                    height: 40,
                    child: TextField(
                      decoration: InputDecoration(
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(5)),
                            borderSide: BorderSide.none
                        ),
                        hintText: "请输入",
                        isDense: true,
                        filled: true,
                        fillColor: ThemeVars.colorBackground,
                        suffixIcon: SizedBox(
                          child: Icon(Icons.search, size: 20,),
                        ),
                      ),
                      style: TextStyle(fontSize: 14),
                    ),
                  )
              )
          ),
          Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.only(top: 60, left: ThemeVars.paddingPage, right: ThemeVars.paddingPage),
            child: RefreshIndicator(
              onRefresh: _refresh,
              child: _list.isEmpty ? ListView(
                children: [EmptyData()],
              ) : ListView.separated(
                controller: _scrollController,
                physics: const AlwaysScrollableScrollPhysics(),
                itemBuilder: (BuildContext context, int index) {
                  return ListItem(
                    info: _list[index],
                    onTap: () {
                      Stacker.pushNamed(Keys.DEVICE_LOCK_FINGERPRINT_DETAIL, arguments: {...widget.info, ..._list[index]}).then((refresh) {
                        if (refresh != null && refresh == true) {
                          _getFingerprints();
                        }
                      });
                    },
                    onLongPress: () {
                      _delFingerprint(_list[index]["fingerprintId"]);
                    },
                  );
                },
                separatorBuilder: (BuildContext context, int index) {
                  return const SizedBox(height: 12,);
                },
                itemCount: _list.length,
              ),
            ),
          ),
        ]
    );
  }

}